package com.yc.web.servlets.admin;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.yc.bean.Food;
import com.yc.model.JsonModel;
import com.yc.web.servlets.BaseServlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author zwei
 * @create 2024-06-21 20:15
 */
@WebServlet("/admin/food.action")
@MultipartConfig
public class foodServlet extends BaseServlet {
    // OSS 配置信息
    private static final String endpoint = "https://oss-cn-beijing.aliyuncs.com"; // OSS 外网节点或自定义域名
    private static final String accessKeyId = "LTAI5tMaMpqNrQHS5ums69Mr";
    private static final String accessKeySecret = "qrCGpsNCirvOSM8wrhnj97hSMO41qw";
    private static final String bucketName = "daiwei001";
    public void addfood(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException, InvocationTargetException, InstantiationException, IllegalAccessException {
        // 获取上传的文件
        Part filePart = req.getPart("file");
        String fileName = filePart.getSubmittedFileName();
        JsonModel jm=new JsonModel();
        if (fileName==null){
            jm.setCode(0);
            jm.setError("请选择图片");
            super.writeJson(jm,resp);
            return;
        }
        InputStream fileContent = filePart.getInputStream();
        // 生成唯一的文件名
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String objectName = uuid + "_" + fileName;
        System.out.println(objectName);
        // 上传文件到 OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(filePart.getSize());
        ossClient.putObject(bucketName, objectName, fileContent, metadata);
        ossClient.shutdown();
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + objectName;
        System.out.println(url);
//        HttpSession session=req.getSession();
//        session.setAttribute("url",url);

        Food food=super.parseObjectFromRequest(req,Food.class);

        if (food.getRemark()==null&&food.getFood_name()==null&&food.getFoodtype_id()==null){
            jm.setCode(0);
            jm.setError("请补充数据");
            super.writeJson(jm,resp);
            return;
        }
        if (food.getPrice()==0&&food.getDiscount()==0){
            jm.setCode(0);
            jm.setError("请补充数据");
            super.writeJson(jm,resp);
            return;
        }
        String sql1="select * from tb_food where food_name=?";
        List<Food>list=dbHelper.select(Food.class,sql1,food.getFood_name());
        if (!list.isEmpty()){
            jm.setCode(0);
            jm.setError("该菜品已存在,无需重复添加");
            super.writeJson(jm,resp);
            return;
        }
        String sql="insert  into tb_food (food_name, foodType_id, price, discount, remark, img, create_date, update_date, disabled) values (?,?,?,?,?,?,?,?,?)";
        int result=dbHelper.doUpdate(sql,food.getFood_name(),food.getFoodtype_id(),food.getPrice(),food.getDiscount(),food.getRemark(),url,LocalDateTime.now(),LocalDateTime.now(),0);
        jm.setCode(1);
        super.writeJson(jm,resp);
    }
    public void updatetest(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "添加成功");
        super.writeObjectToJson(map, resp);
    }
    public void getAllFoods(HttpServletRequest  req, HttpServletResponse resp) throws InvocationTargetException, InstantiationException, IllegalAccessException, IOException {
        int page=1;
        int limit=10;
        if (req.getParameter("page")!=null){
            page= Integer.parseInt(req.getParameter("page"));
        }
        if (req.getParameter("limit")!=null){
            limit= Integer.parseInt(req.getParameter("limit"));
        }
        String sql1 = "select*from tb_food where 1=1";
        String sql2 = "select count(*) as total from tb_food where 1=1";
        Food food=super.parseObjectFromRequest(req,Food.class);
        List<Object> params = new ArrayList<>();
        if (food.getFood_name()!= null) {
            sql1 += " and food_name=? ";
            sql2 += " and food_name=? ";
            params.add(food.getFood_name());
        }
        if (food.getFoodtype_id() != null && !"".equals(food.getFoodtype_id())) {
            sql1 += " and foodtype_id like '%" + food.getFoodtype_id() + "%'  ";
            sql2 += " and foodtype_id like '%" + food.getFoodtype_id() + "%'  ";
        }
        int skip = (page - 1) * limit;
        List<Food> list = dbHelper.select(Food.class,sql1 + " ORDER BY id DESC limit " + limit + " offset " + skip,params.toArray());
        Map<String, Object> map = new HashMap<String, Object>();
        System.out.println(list);
        List<Map<String,Object>> result = dbHelper.select(sql2,params.toArray());
        System.out.println(result);
        int total = Integer.parseInt(result.get(0).get("total").toString());
        map.put("code", 0);
        map.put("msg", "查询菜品成功");
        map.put("count", total);
        map.put("data", list);
        super.writeObjectToJson(map, resp);
    }
    public void delFood(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        String login_name=req.getParameter("id");
        String sql="delete from tb_food where id=?";
        JsonModel jm=new JsonModel();
        int result=dbHelper.doUpdate(sql,login_name);
        Map<String,Object>map=new HashMap<>();
        map.put("code",0);
        map.put("msg","删除成功");
        super.writeObjectToJson(map,resp);
    }
    public void delFood1(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("idsStr");
        String[] parts = id.split(",");
        String sql = "delete from tb_food where id=?";
        for (String str : parts) {
            dbHelper.doUpdate(sql,str);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "删除用户成功");
        super.writeObjectToJson(map, resp);
    }
    public void stopFood(HttpServletRequest req,HttpServletResponse resp) throws InvocationTargetException, InstantiationException, IllegalAccessException, IOException {
        Map<String,Object>map=new HashMap<>();
        String id=req.getParameter("idsStr");
        String [] parts=id.split(",");
        String sql="update tb_food set disabled=? where id=?";
        for (String str:parts){
            dbHelper.doUpdate(sql,1,str);
        }
        map.put("code",0);
        map.put("msg","修改成功");
        super.writeObjectToJson(map,resp);
    }
    public void startFood(HttpServletRequest req,HttpServletResponse resp) throws InvocationTargetException, InstantiationException, IllegalAccessException, IOException {
        Map<String,Object>map=new HashMap<>();
        String id=req.getParameter("idsStr");
        String [] parts=id.split(",");
        String sql="update tb_food set disabled=? where id=?";
        for (String str:parts){
            dbHelper.doUpdate(sql,0,str);
        }
        map.put("code",0);
        map.put("msg","修改成功");
        super.writeObjectToJson(map,resp);
    }
    public void updateFood(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        JsonModel jm=new JsonModel();
        Integer disabled= Integer.valueOf(req.getParameter("disabled"));
        if (disabled==0){
            disabled=1;
        }else {
            disabled=0;
        }
        Integer id= Integer.valueOf(req.getParameter("id"));
        String sql="update tb_food set disabled=?,update_date=? where id=?";
        dbHelper.doUpdate(sql,disabled,LocalDateTime.now(),id);
        jm.setCode(1);
        super.writeJson(jm,resp);
    }
    public void update(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException, InvocationTargetException, InstantiationException, IllegalAccessException {
        // 获取上传的文件
        Part filePart = req.getPart("file");
        String fileName = filePart.getSubmittedFileName();
        JsonModel jm=new JsonModel();
        if (fileName==null){
            jm.setCode(0);
            jm.setError("请选择图片");
            super.writeJson(jm,resp);
            return;
        }
        InputStream fileContent = filePart.getInputStream();
        // 生成唯一的文件名
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String objectName = uuid + "_" + fileName;
        System.out.println(objectName);
        // 上传文件到 OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(filePart.getSize());
        ossClient.putObject(bucketName, objectName, fileContent, metadata);
        ossClient.shutdown();
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + objectName;
        System.out.println(url);
        Food food=super.parseObjectFromRequest(req,Food.class);
        if (food.getRemark()==null||food.getFood_name()==null||food.getFoodtype_id()==null){
            jm.setCode(0);
            jm.setError("请补充数据");
            super.writeJson(jm,resp);
            return;
        }
        if (food.getPrice()==0||food.getDiscount()==0){
            jm.setCode(0);
            jm.setError("请补充数据");
            super.writeJson(jm,resp);
            return;
        }
        String sql="update tb_food set food_name=?,foodtype_id=?,price=?,discount=?,remark=?,img=?,update_date=? where id=?";
        int result=dbHelper.doUpdate(sql,food.getFood_name(),food.getFoodtype_id(),food.getPrice(),food.getDiscount(),food.getRemark(),url,LocalDateTime.now(),food.getId());
        if(result!=0){
            jm.setCode(1);
        }
        super.writeJson(jm,resp);
    }
    public void getfood(HttpServletRequest req,HttpServletResponse resp) throws InvocationTargetException, InstantiationException, IllegalAccessException, IOException {
        String id=req.getParameter("id");
        String sql="select* from tb_food where id=? ";
        List<Food>list=dbHelper.select(Food.class,sql,id);
        Food food=list.get(0);
        JsonModel jm=new JsonModel();
        jm.setCode(1);
        jm.setObj(food);
        super.writeJson(jm,resp);
    }
}
